package com.zat.mes.andrmes.service;

import android.accessibilityservice.AccessibilityService;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.util.Log;
import android.view.KeyEvent;
import android.view.accessibility.AccessibilityEvent;
import android.widget.Toast;

import com.google.gson.Gson;
import com.love.zywanandroid.retrofit.RetrofitManager;
import com.love.zywanandroid.retrofit.api.ApiService;
import com.zat.mes.andrmes.BaseApplication;
import com.zat.mes.andrmes.R;
import com.zat.mes.andrmes.data.LoginResultBean;
import com.zat.mes.andrmes.dofun.work.DayWorkScanActivity;
import com.zat.mes.andrmes.data.PackBean;
import com.zat.mes.andrmes.data.WorkRecordInsertResult;
import com.zat.mes.andrmes.global.CompanionType;
import com.zat.mes.andrmes.data.BaseResponse;
import com.zat.mes.andrmes.retrofit.callback.MesCallBack;
import com.zat.mes.andrmes.utils.ActivityUtils;
import com.zat.mes.andrmes.utils.PreferencesUtil;
import com.zat.mes.andrmes.utils.ReadCardUtils;

import org.jetbrains.annotations.Nullable;
import org.json.JSONObject;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Response;

public class ReadCardService extends AccessibilityService {

    private static final String TAG = ReadCardService.class.getSimpleName();
    private ReadCardUtils readCardUtils;
    private long empId = 0;
    private String empName = "";

    @Override
    public void onAccessibilityEvent(AccessibilityEvent event) {
        if (readCardUtils == null) {
            readCardUtils = new ReadCardUtils();
            initRead();
        }
        Log.e(TAG, "onAccessibilityEvent --> " + event);
    }

    private void initRead() {

        LoginResultBean loginResultBean = new Gson().fromJson(
                PreferencesUtil.INSTANCE.getString(CompanionType.LOGIN_RESULT, ""), LoginResultBean.class);
        empId = loginResultBean.getEmpid();
        empName = loginResultBean.getEmpname();
        readCardUtils.setReadSuccessListener(new ReadCardUtils.OnReadSuccessListener() {
            @Override
            public void onScanSuccess(String barcode) {
                Log.e(TAG, "barcode: " + barcode);
                boolean has = ActivityUtils.has("com.zat.mes.andrmes.dofun.work.DayWorkScanActivity");
                Log.e(TAG, "activity-has" + has);

//                PowerManager powerManager = (PowerManager)getSystemService(Context.POWER_SERVICE);
//                boolean ifOpen = powerManager.isScreenOn();
//                Log.e(TAG, "activity-has" + "屏幕是否亮："+ifOpen);
                if (has && !DayWorkScanActivity.getDayWorkScanActivityShow()) {
                    //当前在DayWorkScanActivity 页面，并且锁屏状态，
                    Log.e(TAG, "activity-has" + "打开了刷卡页面，并且锁屏");
                    if (barcode.length() == 8 || barcode.length() == 10) {
                        //叫唤
                        Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
                        Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);
                        r.play();
                        RetrofitManager.Companion.apiService(ApiService.class)
                                .getPackByRFRD(barcode)
                                .enqueue(new MesCallBack<BaseResponse<PackBean>>() {
                                    @Override
                                    public void onSuccessful(@Nullable Call<BaseResponse<PackBean>> call, @Nullable Response<BaseResponse<PackBean>> response) {
                                        if (response.body().getSuccess()) {
                                            PackBean it = response.body().getResult();
                                            if (it != null) {
                                                try {
                                                    JSONObject jsonObject = new JSONObject();
                                                    jsonObject.put("empId", empId);
                                                    jsonObject.put("empName", empName);
                                                    jsonObject.put("packId", it.getPackId());
                                                    jsonObject.put("packNo", it.getPackNO());
                                                    jsonObject.put("orderId", it.getOrderId());
                                                    jsonObject.put("styleNO", it.getStyleNO());
                                                    jsonObject.put("productName", it.getProductName());
                                                    jsonObject.put("color", it.getColor());
                                                    jsonObject.put("size", it.getSize());
                                                    jsonObject.put("quantity", it.getQuantity());
                                                    //新增 日生产计划
                                                    RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonObject.toString());
                                                    RetrofitManager.Companion.apiService(ApiService.class)
                                                            .insertRecord(requestBody)
                                                            .enqueue(new MesCallBack<BaseResponse<WorkRecordInsertResult>>() {
                                                                @Override
                                                                public void onSuccessful(@Nullable Call<BaseResponse<WorkRecordInsertResult>> call, @Nullable Response<BaseResponse<WorkRecordInsertResult>> response) {
                                                                    if (response.body().getSuccess()) {
                                                                        Toast.makeText(BaseApplication.Companion.getContext(), getString(R.string.work_success), Toast.LENGTH_LONG).show();
                                                                    }
                                                                }
                                                            });
                                                } catch (Exception e) {
                                                }


                                            } else {
                                                Toast.makeText(BaseApplication.Companion.getContext(), getString(R.string.swip_card_fail), Toast.LENGTH_LONG).show();
                                            }
                                        } else {
                                            Toast.makeText(BaseApplication.Companion.getContext(), getString(R.string.swip_card_fail), Toast.LENGTH_LONG).show();
                                        }
                                    }
                                });
                    }
                }
            }
        });
    }


    @Override
    public void onInterrupt() {
        Log.e(TAG, "onInterrupt");
    }

    /**
     * 复写这个方法可以捕获按键事件
     *
     * @param event
     * @return
     */
    @Override
    protected boolean onKeyEvent(KeyEvent event) {
        int keyCode = event.getKeyCode();
//        Log.e(TAG, "keyEvent:" + event + "keyCode: " + keyCode + "char: " + KeyEvent.keyCodeToString(keyCode));
        if (ReadCardUtils.isInputFromReader(this, event)) {
            if (readCardUtils != null) {
                readCardUtils.resolveKeyEvent(event);
            }
        }
        return super.onKeyEvent(event);
    }

    @Override
    public void onDestroy() {
        if (readCardUtils != null) {
            readCardUtils.removeScanSuccessListener();
            readCardUtils = null;
        }
        super.onDestroy();
    }
}